package com.bdqn.t320.bootsecurity.service;

import com.bdqn.t320.bootsecurity.entity.Role;
import com.bdqn.t320.bootsecurity.entity.User;
import com.bdqn.t320.bootsecurity.repository.UserRepository;
import com.bdqn.t320.bootsecurity.vo.UserInfo;
import com.bdqn.t320.bootsecurity.vo.UserRight;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImp implements UserService {
    @Resource
    UserRepository userRepository;

    @Override
    public User getUser(Long usrId) {
        return userRepository.findById(usrId).get();
    }

    @Override
    public User findByUsrNameAndUsrPasswordBiz(String usrName, String password) {
        return userRepository.findByUsrNameAndUsrPassword(usrName, password);
    }

    @Override
    public Page<User> findPageByMap(Map param, Pageable pageable) {
        return userRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (param.get("usrName") != null && param.get("usrName").toString().length() > 0) { //动态 SQL
                    predicates.add(cb.like(root.get("usrName"), "%" + param.get("usrName") + "%"));
                }
                if (param.get("roleId") != null && !param.get("roleId").equals("0")) {
                    //predicates.add(cb.equal(root.get("role"), param.get("roleId")));
                    Role role = new Role();
                    role.setRoleId(Long.valueOf(param.get("roleId").toString()));
                    predicates.add(cb.equal(root.get("role"), role));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
    }


    public UserDetails loadUserByUsername(String username){
        UserInfo userInfo = userRepository.getUserInfo(username);
        if(userInfo==null){
            throw  new UsernameNotFoundException("用户名不存在");
        }
        List<UserRight> listUserRight = userRepository.getUserRightByUserName(username);
        List<String> authorities = new ArrayList<>();
        for (UserRight userRight : listUserRight) {
            authorities.add("/crm" + userRight.getRightUrl());
        }
        String str = String.join(",", authorities);
        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList(str);
        return org.springframework.security.core.userdetails.User.withUsername(userInfo.getUsrName()).password(userInfo.getUsrPassword()).roles(userInfo.getRoleName()).authorities(list).build();
    }
}
